package com.zsr.xmall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsr.common.constant.auth.AuthSourceTypeConstant;
import com.zsr.common.to.member.MemberUserLoginTO;
import com.zsr.common.to.member.MemberUserRegisterTO;
import com.zsr.common.utils.HttpUtils;
import com.zsr.common.utils.PageUtils;
import com.zsr.common.utils.Query;
import com.zsr.common.vo.auth.BaseSocialUser;
import com.zsr.xmall.member.dao.MemberDao;
import com.zsr.xmall.member.dao.MemberLevelDao;
import com.zsr.xmall.member.entity.MemberEntity;
import com.zsr.xmall.member.entity.MemberLevelEntity;
import com.zsr.xmall.member.exception.PhoneExistException;
import com.zsr.xmall.member.exception.UserNameExistException;
import com.zsr.xmall.member.service.MemberService;
import org.apache.commons.lang.ObjectUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(MemberUserRegisterTO to) {
        MemberEntity member = new MemberEntity();
        //设置默认等级
        MemberLevelEntity memberLevelEntity = memberLevelDao.getDefaultLevel();
        member.setLevelId(memberLevelEntity.getId());

        //设置手机号和用户名
        member.setMobile(to.getPhone());
        member.setUsername(to.getUserName());
        member.setNickname(to.getUserName());

        //检查唯一性
        this.checkPhoneUnique(to.getPhone());
        this.checkUserNameUnique(to.getUserName());

        //密码加密存储
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(to.getPassword());
        member.setPassword(encode);


        baseMapper.insert(member);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        Integer count = this.baseMapper.selectCount(new LambdaQueryWrapper<MemberEntity>().eq(MemberEntity::getMobile, phone));
        if (count > 0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public void checkUserNameUnique(String username) throws UserNameExistException {
        Integer count = this.baseMapper.selectCount(new LambdaQueryWrapper<MemberEntity>().eq(MemberEntity::getUsername, username));
        if (count > 0) {
            throw new UserNameExistException();
        }
    }

    @Override
    public MemberEntity login(MemberUserLoginTO userLoginTo) {
        String loginacct = userLoginTo.getLoginacct();
        String password = userLoginTo.getPassword();

        //1.数据库查询 //todo 用户名不能为手机号
        MemberEntity entity = this.baseMapper.selectOne(new LambdaQueryWrapper<MemberEntity>().eq(MemberEntity::getUsername, loginacct)
                .or().eq(MemberEntity::getMobile, loginacct));

        if (entity == null) {
            //登录失败
            return null;
        } else {
            String passwordDb = entity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            boolean matches = passwordEncoder.matches(password, passwordDb);
            return matches ? entity : null;
        }

    }

    @Override
    public MemberEntity login(BaseSocialUser baseSocialUser) throws Exception {
        //登录和组成合并逻辑
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = memberDao.selectOne(new LambdaQueryWrapper<MemberEntity>()
                .eq(MemberEntity::getSocialUid, baseSocialUser.getUid())
                .eq(MemberEntity::getSourceType, baseSocialUser.getSourceType()));
        if (memberEntity != null) {
            memberEntity.setAccessToken(baseSocialUser.getAccess_token());
            memberEntity.setExpiresIn(baseSocialUser.getExpires_in());
            memberDao.updateById(memberEntity);
            return memberEntity;
        } else {
            //2.没有记录需要注册一个
            MemberEntity register = new MemberEntity();

            if (ObjectUtils.equals(baseSocialUser.getSourceType(), AuthSourceTypeConstant.GITEE)) {
                //无需查询接口，信息封装在baseSocialUser
                register.setNickname(baseSocialUser.getName());
                register.setHeader(baseSocialUser.getAvatar_url());
            } else if (ObjectUtils.equals(baseSocialUser.getSourceType(), AuthSourceTypeConstant.WEIBO)) {
                //需查询接口
                //3.查询当前社交用户的社交账号信息（昵称、性别等）
                try {
                    Map<String, String> query = new HashMap<>(2);
                    query.put("access_token", baseSocialUser.getAccess_token());
                    query.put("uid", baseSocialUser.getUid());
                    HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", null, query);
                    if (response.getStatusLine().getStatusCode() == 200) {
                        String json = EntityUtils.toString(response.getEntity());
                        JSONObject jsonObject = JSON.parseObject(json);
                        register.setNickname(jsonObject.getString("name"));
                        String gender = jsonObject.getString("gender");
                        register.setGender("m".equals(gender) ? 1 : 0);
                    }
                } catch (Exception e) {

                }

            }
            register.setSourceType(baseSocialUser.getSourceType());
            register.setSocialUid(baseSocialUser.getUid());
            register.setAccessToken(baseSocialUser.getAccess_token());
            register.setExpiresIn(baseSocialUser.getExpires_in());
            memberDao.insert(register);
            return register;

        }
    }

}